package com.buddy.learn.javasource._socket;

import java.io.*;
import java.net.Socket;
import java.nio.charset.Charset;

/**
 * @author Buddy
 * @date 2021/5/13
 */
public class SocketService implements Runnable {

    private Socket socket;

    public SocketService() {
    }

    SocketService(Socket socket) {
        this.socket = socket;
    }

    @Override
    public void run() {
        System.out.println("SocketService 服务端任务开始执行");
        OutputStream outputStream = null;
        InputStream is = null;
        InputStreamReader isr = null;
        BufferedReader br = null;
        try {
            //接受消息
            socket.setSoTimeout(10000);// 10秒还没有得到数据，直接断开连接
            is = socket.getInputStream();
            isr = new InputStreamReader(is, "UTF-8");
            br = new BufferedReader(isr);
            StringBuffer sb = SocketClient.segmentRead(br);
            socket.shutdownInput();
            System.out.println("SocketService accept info is :" + sb.toString());

            //服务端处理 模拟服务端处理耗时
            Thread.sleep(2000);
            String response = sb.toString();

            //返回处理结果给客户端
            outputStream = socket.getOutputStream();
            byte[] bytes = response.getBytes(Charset.forName("UTF-8"));
            SocketClient.segmentWrite(bytes, outputStream);
            socket.shutdownOutput();

            //关闭流
            SocketClient.close(socket, outputStream, isr, br, is);
            System.out.println("SocketService 服务端任务执行完成");
        } catch (IOException e) {
            System.out.println("SocketService IOException");
            e.printStackTrace();
        } catch (Exception e) {
            System.out.println("SocketService Exception");
            e.printStackTrace();
        } finally {
            try {
                SocketClient.close(socket, outputStream, isr, br, is);
            } catch (IOException e) {
                System.out.println("SocketService IOException");
                e.printStackTrace();
            }
        }
    }
}
